<template>
  <div class="payment-container">
    <NavBar>
      <template #default>确认支付</template>
    </NavBar>

    <div class="payment-content">
      <div class="payment-amount">
        <span class="amount-label">支付金额</span>
        <span class="amount-value">￥{{ formatPrice(totalAmount) }}</span>
      </div>

      <div class="payment-method">
        <div class="method-title">支付方式</div>
        <div class="method-item active">
          <div class="method-icon">
            <el-icon><Money /></el-icon>
          </div>
          <span class="method-name">支付宝支付</span>
          <el-icon class="check-icon"><Select /></el-icon>
        </div>
      </div>

      <div class="order-info">
        <div class="info-item">
          <span class="label">订单号：</span>
          <span class="value">{{ orderId }}</span>
        </div>
      </div>
    </div>

    <!-- 支付二维码容器 -->
    <div ref="payFormContainer" class="qrcode-container" style="display: none;" @click="handleContainerClick">
      <div class="qrcode-wrapper">
        <div class="qrcode-title">请使用支付宝扫码支付</div>
        <div class="qrcode-content">
          <canvas ref="qrcodeCanvas" class="qrcode-canvas"></canvas>
        </div>
        <div class="payment-info">
          <p class="payment-amount">支付金额：<span class="amount">￥{{ formatPrice(totalAmount) }}</span></p>
          <p class="payment-tip">请使用支付宝APP扫码支付</p>
          <p class="payment-notice">支付完成后页面将自动跳转</p>
          <p v-if="qrCodeExpireTime" class="expire-notice">
            二维码有效期：<span class="expire-time">{{ formatExpireTime(qrCodeExpireTime) }}</span>
          </p>
        </div>
      </div>
      <div class="close-button" @click="closePaymentModal">
        <el-icon><Close /></el-icon>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Select, Money, Close } from '@element-plus/icons-vue';
import NavBar from '@/components/common/NavBar.vue';
import { createAlipayOrder, queryPaymentStatus } from '@/api/PaymentApi';
import QRCode from 'qrcode';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const payFormContainer = ref(null);
const qrcodeCanvas = ref(null);
const qrCodeExpireTime = ref(null);
const countdownInterval = ref(null);
const currentTime = ref(Date.now()); // 添加响应式的当前时间

// 从路由参数中获取订单信息
const orderId = route.query.orderId;
const totalAmount = Number(route.query.amount || 0);

// 格式化金额
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
};

// 格式化过期时间
const formatExpireTime = (expireTime) => {
  if (!expireTime) return '';
  const now = currentTime.value; // 使用响应式的当前时间
  const remaining = Math.max(0, expireTime - now);
  const minutes = Math.floor(remaining / 60000);
  const seconds = Math.floor((remaining % 60000) / 1000);
  return `${minutes}分${seconds.toString().padStart(2, '0')}秒`;
};

// 启动倒计时
const startCountdown = (expireTime) => {
  // 清除现有倒计时
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }

  // 每秒更新倒计时
  countdownInterval.value = setInterval(() => {
    if (!qrCodeExpireTime.value) {
      clearInterval(countdownInterval.value);
      return;
    }

    // 更新当前时间，触发响应式更新
    currentTime.value = Date.now();
    const remaining = qrCodeExpireTime.value - currentTime.value;

    if (remaining <= 0) {
      // 二维码已过期
      clearInterval(countdownInterval.value);
      ElMessage.warning('二维码已过期，请重新生成');
      closePaymentModal();
    }
  }, 1000);
};

// 从HTML中提取二维码URL
const extractQRCodeUrl = (htmlString) => {
  try {
    // 创建一个临时DOM元素来解析HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;

    // 查找img标签
    const imgElement = tempDiv.querySelector('img');
    if (imgElement && imgElement.src) {
      return imgElement.src;
    }

    // 如果没找到img标签，尝试用正则表达式提取
    const urlMatch = htmlString.match(/src=['"]([^'"]*qr\.alipay\.com[^'"]*)['"]/);
    if (urlMatch && urlMatch[1]) {
      return urlMatch[1];
    }

    return null;
  } catch (error) {
    console.error('提取二维码URL失败:', error);
    return null;
  }
};

// 缓存相关常量
const QRCODE_CACHE_KEY = 'alipay_qrcode_cache';
const QRCODE_EXPIRE_TIME = 10 * 60 * 1000; // 10分钟

// 保存二维码到本地缓存
const saveQRCodeToCache = (orderId, qrCodeUrl) => {
  const cacheData = {
    orderId,
    qrCodeUrl,
    timestamp: Date.now(),
    expireTime: Date.now() + QRCODE_EXPIRE_TIME
  };
  localStorage.setItem(`${QRCODE_CACHE_KEY}_${orderId}`, JSON.stringify(cacheData));
  console.log('二维码已缓存，过期时间:', new Date(cacheData.expireTime));
};

// 从本地缓存获取二维码
const getQRCodeFromCache = (orderId) => {
  try {
    const cacheStr = localStorage.getItem(`${QRCODE_CACHE_KEY}_${orderId}`);
    if (!cacheStr) return null;

    const cacheData = JSON.parse(cacheStr);
    const now = Date.now();

    // 检查是否过期
    if (now > cacheData.expireTime) {
      localStorage.removeItem(`${QRCODE_CACHE_KEY}_${orderId}`);
      console.log('缓存的二维码已过期');
      return null;
    }

    console.log('从缓存获取二维码，剩余时间:', Math.round((cacheData.expireTime - now) / 1000 / 60), '分钟');
    qrCodeExpireTime.value = cacheData.expireTime;
    currentTime.value = now; // 初始化当前时间
    return cacheData.qrCodeUrl;
  } catch (error) {
    console.error('获取缓存二维码失败:', error);
    return null;
  }
};

// 清除过期的缓存
const clearExpiredCache = () => {
  const keys = Object.keys(localStorage);
  keys.forEach(key => {
    if (key.startsWith(QRCODE_CACHE_KEY)) {
      try {
        const cacheData = JSON.parse(localStorage.getItem(key));
        if (Date.now() > cacheData.expireTime) {
          localStorage.removeItem(key);
          console.log('清除过期缓存:', key);
        }
      } catch (error) {
        localStorage.removeItem(key);
      }
    }
  });
};

// 生成二维码到canvas
const generateQRCode = async (url) => {
  try {
    if (!qrcodeCanvas.value || !url) {
      throw new Error('Canvas元素或URL不存在');
    }

    // 使用qrcode库生成二维码
    await QRCode.toCanvas(qrcodeCanvas.value, url, {
      width: 200,
      height: 200,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    });

    console.log('二维码生成成功');
  } catch (error) {
    console.error('生成二维码失败:', error);
    throw error;
  }
};



// 检查支付状态
const paymentCheckInterval = ref(null);
const startPaymentStatusCheck = () => {
  // 每3秒检查一次支付状态
  paymentCheckInterval.value = setInterval(async () => {
        try {
      const result = await queryPaymentStatus(orderId);

      // 检查支付状态：data为1表示支付成功，0表示未支付
      if (result?.data?.code === 1 && result?.data?.data === 1) {
        // 支付成功，清除缓存和定时器
        localStorage.removeItem(`${QRCODE_CACHE_KEY}_${orderId}`);
        clearInterval(paymentCheckInterval.value);
        if (countdownInterval.value) {
          clearInterval(countdownInterval.value);
        }
        ElMessage.success('支付成功！');
        router.push({
          path: '/payment/result',
          query: {
            status: 'success',
            out_trade_no: orderId,
            total_amount: totalAmount
          }
        });
      }
      // data为0表示未支付，继续轮询
    } catch (error) {
      console.error('查询支付状态失败:', error);
    }
  }, 3000);
};

// 关闭支付弹窗
const closePaymentModal = () => {
  if (payFormContainer.value) {
    payFormContainer.value.style.display = 'none';
  }
  // 清除轮询
  if (paymentCheckInterval.value) {
    clearInterval(paymentCheckInterval.value);
    paymentCheckInterval.value = null;
  }
  // 清除倒计时
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
    countdownInterval.value = null;
  }
  // 返回订单页面
  router.push('/orders');
};

// 处理容器点击（点击背景关闭）
const handleContainerClick = (event) => {
  // 只有点击容器背景时才关闭，避免点击内容区域时关闭
  if (event.target === payFormContainer.value) {
    closePaymentModal();
  }
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (paymentCheckInterval.value) {
    clearInterval(paymentCheckInterval.value);
  }
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
});

// 检查订单参数并自动发起支付
onMounted(async () => {
  if (!orderId || !totalAmount) {
    ElMessage.error('订单信息不完整');
    router.replace('/orders');
    return;
  }

  // 清除过期缓存
  clearExpiredCache();

  // 先尝试从缓存获取二维码
  let qrCodeUrl = getQRCodeFromCache(orderId);

  if (qrCodeUrl) {
    // 使用缓存的二维码
    console.log('使用缓存的二维码');
    try {
      // 显示支付容器
      payFormContainer.value.style.display = 'block';

      // 生成二维码到canvas
      await generateQRCode(qrCodeUrl);

      ElMessage.success('支付二维码已加载，请扫码支付');

      // 启动倒计时
      startCountdown(qrCodeExpireTime.value);

      // 启动轮询检查支付状态
      startPaymentStatusCheck();
      return;
    } catch (error) {
      console.error('使用缓存二维码失败:', error);
      // 如果缓存的二维码有问题，清除缓存并重新请求
      localStorage.removeItem(`${QRCODE_CACHE_KEY}_${orderId}`);
    }
  }

  // 缓存中没有或缓存失效，发起新的支付请求
  try {
    loading.value = true;
    ElMessage.info('正在生成支付二维码...');

    const response = await createAlipayOrder(orderId);

    if (payFormContainer.value && response) {
      // 从HTML响应中提取二维码URL
      qrCodeUrl = extractQRCodeUrl(response);

      if (qrCodeUrl) {
        console.log('从服务器获取到新的二维码URL:', qrCodeUrl);

        // 保存到缓存
        saveQRCodeToCache(orderId, qrCodeUrl);
        qrCodeExpireTime.value = Date.now() + QRCODE_EXPIRE_TIME;
        currentTime.value = Date.now(); // 初始化当前时间

        // 显示支付容器
        payFormContainer.value.style.display = 'block';

        // 生成二维码到canvas
        await generateQRCode(qrCodeUrl);

        ElMessage.success('支付二维码已生成，请扫码支付');

        // 启动倒计时
        startCountdown(qrCodeExpireTime.value);

        // 启动轮询检查支付状态
        startPaymentStatusCheck();
      } else {
        throw new Error('无法从响应中提取二维码URL');
      }
    } else {
      console.error('支付二维码加载失败:', {
        hasContainer: !!payFormContainer.value,
        hasResponse: !!response
      });
      throw new Error('支付二维码加载失败');
    }
  } catch (error) {
    console.error('创建支付订单失败:', error);

    let errorMessage = '创建支付订单失败';
    if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时，请重试或检查网络连接';
    } else if (error.response?.status >= 500) {
      errorMessage = '服务器错误，请稍后重试';
    } else if (error.message?.includes('申请二维码失败')) {
      // 支付宝重复请求错误，尝试使用可能存在的缓存
      const cachedUrl = getQRCodeFromCache(orderId);
      if (cachedUrl) {
        console.log('支付宝拒绝重复请求，使用缓存二维码');
        try {
          payFormContainer.value.style.display = 'block';
          await generateQRCode(cachedUrl);
          ElMessage.warning('检测到重复请求，已加载之前的二维码');
          // 启动倒计时
          startCountdown(qrCodeExpireTime.value);
          startPaymentStatusCheck();
          return;
        } catch (cacheError) {
          console.error('使用缓存二维码失败:', cacheError);
        }
      }
      errorMessage = '订单已存在有效二维码，请稍后重试或联系客服';
    } else if (error.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);

    // 3秒后返回订单页面
    setTimeout(() => {
      router.push('/orders');
    }, 3000);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 44px;
  padding-bottom: 80px;
}

.payment-content {
  background-color: #fff;
  padding: 20px 16px;
}

.payment-amount {
  text-align: center;
  padding: 20px 0;
}

.amount-label {
  font-size: 16px;
  color: #666;
  margin-right: 8px;
}

.amount-value {
  font-size: 32px;
  font-weight: bold;
  color: #ff5000;
}

.payment-method {
  margin-top: 20px;
}

.method-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f8f8f8;
  border-radius: 8px;
  margin-bottom: 12px;
}

.method-item.active {
  background: #fff5f0;
  border: 1px solid #ff5000;
}

.method-icon {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  background: #fff5f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.method-icon .el-icon {
  font-size: 24px;
  color: #ff5000;
}

.method-name {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.check-icon {
  color: #ff5000;
  font-size: 20px;
}

.order-info {
  margin-top: 20px;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 8px;
}

.info-item {
  display: flex;
  font-size: 14px;
  margin-bottom: 8px;
}

.info-item .label {
  color: #666;
  width: 80px;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.payment-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.pay-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.qrcode-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

/* 二维码显示样式 */
.qrcode-wrapper {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  text-align: center;
  max-width: 400px;
  min-width: 320px;
}

.qrcode-title {
  font-size: 20px;
  font-weight: bold;
  color: #1677ff;
  margin-bottom: 25px;
}

.qrcode-content {
  margin: 25px 0;
  display: flex;
  justify-content: center;
}

.qrcode-canvas {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.payment-info {
  margin-top: 25px;
}

.payment-amount {
  font-size: 18px;
  color: #333;
  margin: 0 0 12px 0;
}

.payment-amount .amount {
  color: #f50;
  font-weight: bold;
  font-size: 20px;
}

.payment-tip {
  font-size: 14px;
  color: #666;
  margin: 8px 0;
}

.payment-notice {
  font-size: 12px;
  color: #999;
  margin: 8px 0 0 0;
}

.expire-notice {
  font-size: 12px;
  color: #ff6b35;
  margin: 8px 0 0 0;
}

.expire-time {
  font-weight: bold;
  color: #ff4d4f;
}

/* 关闭按钮 */
.close-button {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1001;
  transition: background 0.3s ease;
}

.close-button:hover {
  background: rgba(0, 0, 0, 0.8);
}

.close-button .el-icon {
  color: white;
  font-size: 20px;
}
</style>